<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {ElMessage} from 'element-plus'
import http from '../http/index'
import {useRouter} from "vue-router";


const ruleFormRef = ref<FormInstance>()
// 获取路由器
const router = useRouter()


const ruleForm = reactive({
  phone: '',
  username: '',
  pass: '',
  checkPass: ''
})


//  手机号校验
const validatePhone = (rule: any, value: any, callback: any) => {
  const reg = /^[1][3-9][0-9]{9}$/;
  if (value == '' || value == undefined || value == null) {
    callback(new Error('请输入手机号'))
  } else {
    if ((!reg.test(value)) && value != '') {
      callback(new Error('请输入正确的电话号码'));
    } else {
      callback();
    }
  }
}

// 账号为空校验
const validateUserName = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入账号'))
  } else {
    callback()
  }
}

//  密码为空校验
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== ruleForm.pass) {
    callback(new Error("请输入相同的密码"))
  } else {
    callback()
  }
}


const rules = reactive<FormRules<typeof ruleForm>>({
  phone: [{validator: validatePhone, trigger: 'blur'}],
  username: [{validator: validateUserName, trigger: 'blur'}],
  pass: [{validator: validatePass, trigger: 'blur'}],
  checkPass: [{validator: validatePass2, trigger: 'blur'}],
})


let sendmsg = ref("发送验证码")
let isSend = ref(true)
let verCode = ref('')  // 验证码


//  获取验证码
const sendMessage = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      // 查询手机号是否注册
      http.post('/sdkssm/selectPhone', {phone: ruleForm.phone}).then(request => {
        // @ts-ignore
        if (request.code == 200) {
          sendMe()   // 发送验证码
        } else {
          // @ts-ignore
          ElMessage({type: 'error', message: request.msg})
        }
      })
    } else {
      // 信息未输入警告
      return false
    }
  })
}

//  发送验证码
const sendMe = () => {
  http.post('/sdkssm/sendTest', {phone: ruleForm.phone}).then(request => {
    // @ts-ignore
    if (request.code == 200) {
      // @ts-ignore
      ElMessage({message: '发送成功', type: 'success'})
      verCode.value = request.data
      isSend.value = false;
      let timer = 60;
      sendmsg.value = timer + "s";
      let timeFun = setInterval(() => {
        --timer;
        sendmsg.value = timer + "s";
        if (timer == 0) {
          isSend.value = true;
          sendmsg.value = "重新发送";
          clearInterval(timeFun);
        }
      }, 1000);
    }
  })
}

//  验证码为空
let fromCode = ref('')

//  注册请求
let userRegister = () => {
  http.post('/sdkssm/userRegister',
      {userName: ruleForm.username, password: ruleForm.pass, phonenumber: ruleForm.phone}
  ).then(request => {
    // @ts-ignore
    if (request.code == 200) {
      ElMessage({type: 'success', message: '注册成功'})
      router.push('/')
    } else {
      ElMessage({type: 'error', message: '注册失败'})
    }
  })
}

//  注册
const submitRegister = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      // 验证码为空
      if (fromCode.value == '') {
        ElMessage({type: 'error', message: '请输入验证码'})
        return
      }
      // 验证码错误
      if (fromCode.value != verCode.value) {
        ElMessage({type: 'error', message: '验证码错误'})
        return
      }
      // 注册
      userRegister()
    } else {
      // 信息未输入警告
      return false
    }
  })
}

//  跳转登录页面
let goLogin = () => {
  router.push('/')
}

</script>

<template>
  <div class="login">
    <div class="login-wrap">
      <img class="login-bg1" src="@/assets/login/login_bg1.png"/>
      <img class="login-bg2" src="@/assets/login/login_bg2.png"/>
      <img class="login-bg3" src="@/assets/login/login_bg3.png"/>
      <div class="login-form-wrap">
        <!-- 注册from表单
         :rules="rules" 校验规则     status-icon 反馈图标  -->
        <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm" label-width="auto" class="login-form">
          <h3 class="title">Registration Page</h3>
          <el-form-item prop="username">
            <el-input type="text" v-model="ruleForm.username" autocomplete="off" placeholder="账号">
              <template #prefix>
                <el-icon>
                  <User/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="pass">
            <el-input v-model="ruleForm.pass" type="password" autocomplete="off" placeholder="密码">
              <template #prefix>
                <el-icon>
                  <Unlock/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="checkPass">
            <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" placeholder="请再次输入密码">
              <template #prefix>
                <el-icon>
                  <Unlock/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="phone">
            <el-input type="text" v-model="ruleForm.phone" autocomplete="off" placeholder="手机号">
              <template #prefix>
                <el-icon>
                  <Phone/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="fromCode" type="text" autocomplete="off" placeholder="验证码"
                      style="width:180px">
              <template #prefix>
                <el-icon>
                  <Cellphone/>
                </el-icon>
              </template>
            </el-input>
            <el-button plain class="buttonMessage" @click="sendMessage(ruleFormRef)" v-if="isSend">获取验证码
            </el-button>
            <el-button class="buttonMessage" v-if="!isSend">{{ sendmsg }}</el-button>
          </el-form-item>
          <el-button class="rigisterButton" type="primary" @click="submitRegister(ruleFormRef)">注册</el-button>
          <el-button class="gologin" @click="goLogin">去登录</el-button>
        </el-form>


      </div>
    </div>

    <!--  底部  -->
    <div class="el-login-footer">
      <span>LinkWeChat Registration Page.</span>
    </div>

  </div>
</template>


<style rel="stylesheet/scss" lang="scss" scoped>
.login {
  margin-top: 9px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-size: cover;
}

.login-wrap {
  position: relative;
  width: 1180px;
  height: 733px;
}

[class*='login-bg'] {
  position: absolute;
  z-index: -1;
}

.login-form-wrap {
  position: relative;
  background: #fff;
  height: 609px;
  top: 62px;
  left: 112px;
}

.login-bg1 {
  top: 0;
  left: 0;
  height: 100%;
}

.login-bg2 {
  top: 62px;
  left: 382px;
  z-index: 10;
}

.login-bg3 {
  top: 220px;
  right: 25px;
  z-index: 20;
}

// 底部
.el-login-footer {
  height: 40px;
  line-height: 10px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
  z-index: 90;
}


// from表单
.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 0 25px 5px 25px;
  position: relative;
  top: 120px;

  .el-input {
    margin-top: 6px;
    height: 35px;
    width: 320px;
  }
}

.title {
  margin: 0px 50px 20px auto;
  text-align: center;
  color: #027dfe;
}

.buttonMessage {
  font-size: 12px;
  margin-left: 20px;
  margin-top: 5px;
}

.rigisterButton {
  margin-top: 2px;
  width: 320px;
}

// 注册按钮
.gologin {
  margin-top: 15px;
  width: 295px;
  border: 2px solid dodgerblue;
  text-align: center;
  color: #027dfe;
}


</style>